#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("智农云瞰");
    this->setWindowIcon(QIcon(":/RIO.png"));

    // 每秒钟更新一次时间
    QTimer* tim = new QTimer(this);
    connect(tim, &QTimer::timeout, this, &Widget::currentimeshow);
    tim->start(1000);

    // 初始化网络管理对象
    manager = new QNetworkAccessManager(this);
    // 设置请求的URL
    request.setUrl(QUrl("http://192.168.4.1/capture?_cb=8888"));
    // 初始化定时器
    timer = new QTimer(this);
    // 定时器触发信号连接到槽函数
    connect(timer, &QTimer::timeout, this, &Widget::onTimeout);
    // 启动定时器，每 100ms 触发一次
    timer->start(100);

    // 初始化 MQTT 客户端
    mqttClient = new QMqttClient(this);

    // 设置 MQTT 连接参数
    mqttClient->setHostname("iot-06z00ilbgenuiy3.mqtt.iothub.aliyuncs.com");  // 主机地址
    mqttClient->setPort(1883);  // 端口号
    mqttClient->setUsername("yyyy&k22l9xRMK4m");  // 用户名
    mqttClient->setPassword("84bb8ee6ac6df43e606699546780945c716a0793fbc125d5289302591a4a79af");  // 密码
    mqttClient->setClientId("k22l9xRMK4m.yyyy|securemode=2,signmethod=hmacsha256,timestamp=1733917458544|");  // 客户端 ID
    //mqttClient->set(QMQTT::MQTTVersion::V3_1_1);
    mqttClient->setKeepAlive(120);
    // 连接信号与槽
    connect(mqttClient, &QMqttClient::connected, this, &Widget::onConnected);
    connect(mqttClient, &QMqttClient::disconnected, this, &Widget::onDisconnected);
    connect(mqttClient, &QMqttClient::messageReceived, this, &Widget::onMessageReceived);

    // 连接到 MQTT 代理
    mqttClient->setCleanSession(true);  // 默认为 true
    mqttClient->connectToHost();

    // 初始化定时器
    watchdogTimer = new QTimer(this);
    watchdogTimer->setInterval(10000);  // 设置10秒超时时间

    // 连接超时信号到槽函数
    connect(watchdogTimer, &QTimer::timeout, this, &Widget::onDeviceTimeout);

    // 初始化在线状态
    isDeviceOnline = false;

    stateflag = false;
}

Widget::~Widget()
{
    delete ui;
    videoWriter.release();
}

void Widget::currentimeshow()
{
    QDateTime currentDateTime = QDateTime::currentDateTime();

    // 格式化日期和时间
    QString formattedDateTime = currentDateTime.toString("yyyy-MM-dd hh:mm:ss");

    // 在标签上显示格式化后的时间
    ui->label_time->setText(formattedDateTime);
    ui->label_time->setFont(QFont("黑体", 20));
}

void Widget::on_pushButton_led_clicked()
{
    if (ui->pushButton_led->text() == "开") {
        ui->pushButton_led->setText("关");
        publishDeviceStatus("Led", true);
    } else {
        ui->pushButton_led->setText("开");
        publishDeviceStatus("Led", false);
    }
}

void Widget::on_pushButton_fan_clicked()
{
    if (ui->pushButton_fan->text() == "开") {
        ui->pushButton_fan->setText("关");
        publishDeviceStatus("Fan", true);
    } else {
        ui->pushButton_fan->setText("开");
        publishDeviceStatus("Fan", false);
    }
}

void Widget::on_pushButton_sg90_clicked()
{
    if (ui->pushButton_sg90->text() == "开") {
        ui->pushButton_sg90->setText("关");
        publishDeviceStatus("Sg90", true);
    } else {
        ui->pushButton_sg90->setText("开");
        publishDeviceStatus("Sg90", false);
    }
}

void Widget::on_pushButton_bee_clicked()
{
    if (ui->pushButton_bee->text() == "开") {
        ui->pushButton_bee->setText("关");
        publishDeviceStatus("Bee", true);
    } else {
        ui->pushButton_bee->setText("开");
        publishDeviceStatus("Bee", false);
    }
}

void Widget::onTimeout()
{
    // 每次定时器触发，发送 GET 请求
    QNetworkReply *reply = manager->get(request);

    // 连接请求完成信号到槽函数
    connect(reply, &QNetworkReply::finished, this, &Widget::onImageDownloaded);
}

void Widget::onImageDownloaded()
{
    // 获取完成的网络请求对象
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());

    if (reply) {
        // 读取返回的图像数据
        QByteArray imageData = reply->readAll();

        // 将图像数据加载到 QPixmap 对象中
        QPixmap pixmap;
        if (pixmap.loadFromData(imageData)) {
            // 缩放并设置到 QLabel 上
            ui->label_camera->setPixmap(pixmap.scaled(frameWidth, frameHeight, Qt::KeepAspectRatio));

            // 将 QPixmap 转换为 OpenCV 的 Mat
            QImage qImage = pixmap.toImage().convertToFormat(QImage::Format_RGB888);
            cv::Mat frame(qImage.height(), qImage.width(), CV_8UC3, (void*)qImage.bits(), qImage.bytesPerLine());
            cv::cvtColor(frame, frame, cv::COLOR_RGB2BGR); // 转换为 BGR 格式

            // 检查图像的尺寸是否匹配
            cv::Size videoSize(frame.cols, frame.rows); // 确保视频尺寸与图像一致

            // 检查图像通道数，并设置 isColor 参数
            bool isColor = (frame.channels() == 3);  // 如果是三通道（RGB），则为 true，否则为 false

            // 初始化视频写入器（如果未初始化）
            if (!isVideoWriterInitialized) {
                QString videoPath = "/home/hqyj/Desktop/output.avi"; // 视频保存路径

                // 检查文件路径是否为空
                if (videoPath.isEmpty()) {
                    qDebug() << "Video path is empty!";
                    return;
                }

                // 打印文件路径以确认其值
                qDebug() << "Video path:" << videoPath;

                // 确保目录存在并可写
                QDir dir = QFileInfo(videoPath).absoluteDir();
                if (!dir.exists() && !dir.mkpath(".")) {
                    qDebug() << "Failed to create directory for video file!";
                    return;
                }

                // 尝试使用不同的编码格式，MJPEG 和 XVID 都是常见的选择
                videoWriter.open(videoPath.toStdString(),
                                 cv::VideoWriter::fourcc('M', 'J', 'P', 'G'),  // MJPEG 编码格式
                                 fps,
                                 videoSize, isColor);  // 根据图像的通道数设置 isColor

                if (!videoWriter.isOpened()) {
                    qDebug() << "Failed to open video writer!";
                    return;
                }
                isVideoWriterInitialized = true;
                qDebug() << "Video writer initialized.";
            }

            // 写入视频帧
            videoWriter.write(frame);
        }

        // 清理网络请求对象
        reply->deleteLater();
    }
}

void Widget::on_pushButton_clicked()
{
    // 截图
    QPixmap screenshot = ui->label_camera->grab();
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save Screenshot"), "", tr("PNG Files (*.png);;JPEG Files (*.jpg *.jpeg);;BMP Files (*.bmp)"));
    if (!fileName.isEmpty()) {
        screenshot.save(fileName);
    }
    qDebug() << "Photo saved!";
}

void Widget::on_pushButton_2_clicked()
{
    // 结束录制
    if (isVideoWriterInitialized) {
        videoWriter.release(); // 释放视频写入器
        isVideoWriterInitialized = false;
        QMessageBox::information(this, "提示", "录制已完成");
    }
    qDebug() << "Video saved!";
}

// 连接成功时
void Widget::onConnected()
{
    qDebug() << "Connected to MQTT Broker";
    ui->label_cloud->setText("在线");
    ui->label_cloud->setStyleSheet("color: green;");

    //已经订阅了
    //QString topic = "/k22l9xRMK4m/yyyy/user/update";  // 你的设备和产品信息
    //mqttClient->subscribe(topic,0);
}

// 连接断开时
void Widget::onDisconnected()
{
    qDebug() << "Disconnected from MQTT Broker";
    ui->label_cloud->setText("离线");
    ui->label_cloud->setStyleSheet("color: red;");
}

// 接收到消息时
void Widget::onMessageReceived(const QByteArray &message)
{
    watchdogTimer->start();
    // 如果之前是离线状态，更新为在线状态
    if (!isDeviceOnline) {
        isDeviceOnline = true;
        showDeviceStatus(true);  // 更新UI显示为在线
    }

    // 打印接收到的原始消息
    qDebug() << "Message received:" << message;

    // 解析 JSON 消息
    QJsonDocument jsonDoc = QJsonDocument::fromJson(message);
    if (jsonDoc.isNull() || !jsonDoc.isObject()) {
        qDebug() << "Invalid JSON message!";
        return;
    }

    QJsonObject jsonObj = jsonDoc.object();

    // 提取 items 字段
    if (jsonObj.contains("items") && jsonObj["items"].isObject()) {
        QJsonObject itemsObj = jsonObj["items"].toObject();

        // 提取温度值
        if (itemsObj.contains("CurrentTemperature") && itemsObj["CurrentTemperature"].isObject()) {
            QJsonObject tempObj = itemsObj["CurrentTemperature"].toObject();
            if (tempObj.contains("value")) {
                temperature = tempObj["value"].toInt();
                ui->lcdNumber_air1->display(QString::number(temperature));
            }
        }
        // 提取湿度值
        if (itemsObj.contains("Humidity") && itemsObj["Humidity"].isObject()) {
            QJsonObject humidityObj = itemsObj["Humidity"].toObject();
            if (humidityObj.contains("value")) {
                humidity = humidityObj["value"].toInt();
                ui->lcdNumber_air2->display(QString::number(humidity));
            }
        }
        // 提取光照强度
        if (itemsObj.contains("Light") && itemsObj["Light"].isObject()) {
            QJsonObject lightObj = itemsObj["Light"].toObject();
            if (lightObj.contains("value")) {
                light = lightObj["value"].toInt();
                ui->lcdNumber_light->display(QString::number(light));
            }
        }
        // 提取烟雾浓度
        if (itemsObj.contains("Co") && itemsObj["Co"].isObject()) {
            QJsonObject coxObj = itemsObj["Co"].toObject();
            if (coxObj.contains("value")) {
                cox = coxObj["value"].toDouble(); // 获取浮点数值
                ui->lcdNumber_cox->display(QString::number(cox, 'f', 2)); // 显示两位小数
            }
        }

        if (itemsObj.contains("Fan") && itemsObj["Fan"].isObject()) {
            QJsonObject fanObj = itemsObj["Fan"].toObject();
            if (fanObj.contains("value"))
                 fan = fanObj["value"].toInt() == 1;
        }
        if (itemsObj.contains("Led") && itemsObj["Led"].isObject()) {
            QJsonObject ledObj = itemsObj["Led"].toObject();
            if (ledObj.contains("value"))
                 led = ledObj["value"].toInt() == 1;
        }
        if (itemsObj.contains("Sg90") && itemsObj["Sg90"].isObject()) {
            QJsonObject sg90Obj = itemsObj["Sg90"].toObject();
            if (sg90Obj.contains("value"))
                 sg90 = sg90Obj["value"].toInt() == 1;
        }
        if (itemsObj.contains("Bee") && itemsObj["Bee"].isObject()) {
            QJsonObject beeObj = itemsObj["Bee"].toObject();
            if (beeObj.contains("value"))
                 bee = beeObj["value"].toInt() == 1;
        }
        ui->label_fan->setText(fan ? "开启" : "关闭");
        ui->label_led->setText(led ? "开启" : "关闭");
        ui->label_sg90->setText(sg90 ? "开启" : "关闭");
        ui->label_bee->setText(bee ? "开启" : "关闭");
    }

    if (stateflag) {
        if (endflag) {
            endflag = false;
            autocontrol();
            endflag = true;
        }
        ui->pushButton_fan->setDisabled(true);
        ui->pushButton_led->setDisabled(true);
        ui->pushButton_sg90->setDisabled(true);
        ui->pushButton_bee->setDisabled(true);
    } else {
        ui->pushButton_fan->setDisabled(false);
        ui->pushButton_led->setDisabled(false);
        ui->pushButton_sg90->setDisabled(false);
        ui->pushButton_bee->setDisabled(false);
    }
}

// 控制设备状态并发布消息
void Widget::publishDeviceStatus(const QString &deviceName, bool state)
{
    QString topic = "/sys/k22l9xRMK4m/yyyy/thing/event/property/post";
    qint64 id = 1734681857701;

    // 构建 JSON 数据
    QJsonObject params;
    if (deviceName == "Led") {
        params["Led"] = state ? 1 : 0;
    } else if (deviceName == "Fan") {
        params["Fan"] = state ? 1 : 0;
    } else if (deviceName == "Sg90") {
        params["Sg90"] = state ? 1 : 0;
    } else if (deviceName == "Bee") {
        params["Bee"] = state ? 1 : 0;
    }

    QJsonObject payload;
    payload["id"] = id;  // 设置 id
    payload["params"] = params;
    payload["version"] = "1.0";
    payload["method"] = "thing.event.property.post";

    // 将 JSON 对象转为 QByteArray
    QJsonDocument doc(payload);
    QByteArray payloadData = doc.toJson();

    // 发布消息
    mqttClient->publish(topic, payloadData);
    qDebug() << "Message send:" << payloadData;
}

void Widget::onDeviceTimeout()
{
    if (isDeviceOnline) {
        isDeviceOnline = false;
        showDeviceStatus(false);  // 更新UI显示为离线
    }
    qDebug() << "Device is offline.";
}

void Widget::showDeviceStatus(bool online) {
    if (online) {
        ui->label_stm->setText("在线");
        ui->label_stm->setStyleSheet("color: green;");
    } else {
        ui->label_stm->setText("离线");
        ui->label_stm->setStyleSheet("color: red;");
    }
}

void Widget::on_pushButton_auto_clicked()
{
    // 切换模式标志
    stateflag = !stateflag;

    // 根据模式更新按钮显示和逻辑
    if (stateflag) {
        ui->pushButton_auto->setText("自动");
    } else {
        ui->pushButton_auto->setText("手动");
    }
}

void Widget::autocontrol()
{
    // 根据温度控制设备
    if (temperature > 40 && fan == false) {
        publishDeviceStatus("Fan", true);
    } else if (temperature < 40 && fan == true) {
        publishDeviceStatus("Fan", false);
    }

    // 根据光照强度控制设备
    if (light < 20 && led == false) {
        publishDeviceStatus("Led", true);
    }else if (light > 20 && led == true) {
        publishDeviceStatus("Led", false);
    }

    // 根据烟雾浓度控制设备
    if (cox > 10 && fan == false && bee == false) {
        publishDeviceStatus("Fan", true);
        publishDeviceStatus("Bee", true);
    }else if (cox < 10 && fan == true && bee == true) {
        publishDeviceStatus("Fan", false);
        publishDeviceStatus("Bee", false);
    }

    // 根据湿度控制设备
    if (humidity < 10 && sg90 == false) {
        publishDeviceStatus("Sg90", true);
    }else if (humidity > 10 && sg90 == true) {
        publishDeviceStatus("Sg90", false);
    }

//    QThread::sleep(3); //延迟3s
}

